/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2019 All Rights Reserved.
 */
package javabasics.thread.executors;

import java.util.concurrent.*;

/**
 * @author zhaorongzhang
 * @version Id: ExecutorService.java, v 0.1 2019/6/7 23:01 zhaorongzhang Exp $$
 */
public class ExecutorService {

    public static void main(String[] args) {
        /**
         * 创建方式
         */
        // 创建一个缓冲池，缓冲池容量大小为Integer.MAX_VALUE
        Executors.newCachedThreadPool();
        // 创建一个容量为1的缓冲池
        Executors.newSingleThreadExecutor();
        // 创建固定容量大小的缓冲池
        Executors.newFixedThreadPool(10);

        // 自定义线程池参数
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 5,
                TimeUnit.HOURS, new LinkedBlockingDeque<>());

        // 执行 thread
        for (int i = 0; i < 100; i++) {
            MyTask myTask = new MyTask(i);
            executor.execute(myTask);
            System.out.println("线程池中线程数目：" + executor.getPoolSize() +
                    ",队列中等待执行的任务数目：" + executor.getQueue().size() +
                    ",已执行完别的任务数目：" + executor.getCompletedTaskCount());
        }
        executor.shutdown();
    }

    static class MyTask implements Runnable {
        private int taskNum;

        public MyTask(int num) {
            this.taskNum = num;
        }

        @Override
        public void run() {
            System.out.println("正在执行task " + taskNum);
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task " + taskNum + "执行完毕");
        }
    }

}